package com.yiba.vpn.utils;

import android.support.annotation.NonNull;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;


public class RxBus {
    private static final String TAG = RxBus.class.getSimpleName();
    public static boolean DEBUG = false;

    private static class Holder {
        private static final RxBus instance = new RxBus();
    }

    public static RxBus get() {
        return Holder.instance;
    }

    private RxBus() {
    }

    private ConcurrentHashMap<Object, CopyOnWriteArrayList<FlowableProcessor>> flowMap = new ConcurrentHashMap<>();

    public <T> FlowableProcessor<T> register(@NonNull Object tag, @NonNull Class<T> clazz) {
        CopyOnWriteArrayList<FlowableProcessor> flowList = flowMap.get(tag);
        if (null == flowList) {
            flowList = new CopyOnWriteArrayList<>();
            flowMap.put(tag, flowList);
        }

        FlowableProcessor<T> flow;
        flowList.add(flow = PublishProcessor.create());
        return flow;

    }

    public void unregister(@NonNull Object tag, @NonNull FlowableProcessor observable) {
        List<FlowableProcessor> flowList = flowMap.get(tag);
        if (null != flowList) {
            if (observable != null && flowList.contains(observable)) {
                flowList.remove(observable);
            }
        }
        if ((flowList == null || flowList.size() == 0) && flowMap.contains(tag)) {
            flowMap.remove(tag);
        }
    }


    public void post(@NonNull Object content) {
        post(content.getClass().getName(), content);
    }

    public void post(@NonNull Object tag, @NonNull Object content) {
        if (flowMap == null) return;
        if (flowMap.get(tag) == null || flowMap.size() == 0) return;
        for (FlowableProcessor flowable : flowMap.get(tag)) {
            if (flowable != null) {
                flowable.onNext(content);
            }
        }

    }

}